package demo2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LeetCode18 {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> list = new ArrayList<>();
        int n = nums.length - 1;
        for (int k = 0; k <= n - 3; ) {
            for (int j = k + 1; j <= n - 2; ) {
                long tar =(long) target - nums[k] - nums[j];
                int left = j + 1, right = n;
                while (left < right) {
                    if (nums[left] + nums[right] < tar) left++;
                    else if (nums[left] + nums[right] > tar) right--;
                    else {
                        list.add(new ArrayList<Integer>(Arrays.asList(nums[k], nums[j], nums[left], nums[right])));
                        left++; right--;
                        while (left < right && nums[left] == nums[left - 1]) left++;
                        while (left < right && nums[right] == nums[right + 1]) right--;
                    }
                }
                j++;
                while (j <= n - 2 && nums[j] == nums[j - 1]) j++;
            }
            k++;
            while (k <= n - 3 && nums[k] == nums[k - 1]) k++;
        }
        return list;
    }
}
